package com.eshop.tools.service.impl;

import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.eshop.exception.BadRequestException;
import com.eshop.tools.domain.vo.EmailVo;
import com.eshop.utils.EncryptUtils;
import com.eshop.dozer.service.IGenerator;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import com.eshop.tools.service.EmailConfigService;
import com.eshop.tools.domain.EmailConfig;
import com.eshop.tools.service.mapper.EmailConfigMapper;
import com.eshop.common.service.impl.BaseServiceImpl;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = { Exception.class })
public class EmailConfigServiceImpl extends BaseServiceImpl<EmailConfigMapper, EmailConfig> implements EmailConfigService
{
    private final IGenerator generator;
    
    @Transactional(rollbackFor = { Exception.class })
    public void update(final EmailConfig emailConfig, final EmailConfig old) {
        try {
            if (!emailConfig.getPass().equals(old.getPass())) {
                emailConfig.setPass(EncryptUtils.desEncrypt(emailConfig.getPass()));
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        this.saveOrUpdate(emailConfig);
    }
    
    public EmailConfig find() {
        final EmailConfig emailConfig = this.list().get(0);
        return emailConfig;
    }
    
    @Transactional(rollbackFor = { Exception.class })
    public void send(final EmailVo emailVo, final EmailConfig emailConfig) {
        if (emailConfig == null) {
            throw new BadRequestException("请先配置，再操作");
        }
        final MailAccount account = new MailAccount();
        final String user = emailConfig.getFromUser().split("@")[0];
        account.setUser(user);
        account.setHost(emailConfig.getHost());
        account.setPort(Integer.valueOf(Integer.parseInt(emailConfig.getPort())));
        account.setAuth(true);
        try {
            account.setPass(EncryptUtils.desDecrypt(emailConfig.getPass()));
        }
        catch (Exception e) {
            throw new BadRequestException(e.getMessage());
        }
        account.setFrom(emailConfig.getUser() + "<" + emailConfig.getFromUser() + ">");
        account.setSslEnable(Boolean.valueOf(true));
        account.setStarttlsEnable(true);
        final String content = emailVo.getContent();
        try {
            final int size = emailVo.getTos().size();
            Mail.create(account).setTos((String[])emailVo.getTos().toArray(new String[size])).setTitle(emailVo.getSubject()).setContent(content).setHtml(true).setUseGlobalSession(false).send();
        }
        catch (Exception e2) {
            throw new BadRequestException(e2.getMessage());
        }
    }
    
    public EmailConfigServiceImpl(final IGenerator generator) {
        this.generator = generator;
    }
}
